var app = getApp();
var util = require('../../utils/util.js');
Page({

  /**
   * 页面的初始数据 
   */
  data: {
    xturl: app.myUlife.ulifeUrl + "/",
    imgdefalut: app.myUlife.ulifeUrl + '/wx/Integral_bg_img.png',//默认图片
    topimage:'',
    ydzx: '../../images/me_medal_icon.png',//默认图片
    activeIndex: 0,
    navList: [{
      name: '积分商城',
      _id: '0',
    },
    {
      name: '成长记录',
      _id: '1',
    }],
   


    prompt: {
      hidden: !0,
      icon: '../../assets/images/iconfont-order-default.png',
      title: '暂无相关书籍',
      text: '没有教师推荐的数据，可以看看家长推荐的优秀书籍',
      gurl: '../../pages/home/home',
      gtype: "switchTab"
    }, 

    page: 1,
    limit: 20,
    totalpage: 0,
    totalnum:0,
    jfsp:[],//积分商品

    showModalStatus: false,//积分兑换弹窗

    username:'',//姓名
    avatarUrl: '',//我的头像
    gender:'',
    sp:{},//被选中的商品
    dhsl:1,//兑换数量
    usejf:0,//需要使用的积分
    jfych:{},//积分与称号
    alljf:0,

    showTSModalStatus:false,//提示弹出
    kyjf:0,//可用积分
    certifaceurl: app.myUlife.ulifeUrl + '/wx/certificate_bg_img.png',//证书图片
    formatDate: '',//当前日期

    showZsModalStatus:false,//证书弹窗
    canvasHidden:true,//画布隐藏
    tempFilePath:'',//证书临时图片


    showsqModalStatus: false,//提示弹出
  },
  
  /** 
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var usid = wx.getStorageSync('usid');
    if (!usid) {
      wx.reLaunch({
        url: '../../pages/login/login'
      })
      return;
    }
    var gender = wx.getStorageSync('gender');
    this.setData({
      gender: gender,
      avatarUrl: wx.getStorageSync('avatarUrl'),
      username: wx.getStorageSync('name')
    });
    //查询顶部图片
    this.gethxtdtopImage();
    //查询可用积分与称号
    this.getMyJfyCh();
    //查询积分商城商品
    this.getShangpinAll();
    this.downlaodimageurl();
  },

  gethxtdtopImage(){
    var that = this;
    wx.request({
      url: app.myUlife.ulifeUrl + 'jfych/getTopImagePic.html',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        var imgurl = res.data.photos;
        if (imgurl) {
          that.setData({
            topimage: that.data.xturl + imgurl,
          })
        }
      }
    })
  },

  getShangpinAll() {
    var that = this;
    var page = that.data.page;
    var limit = that.data.limit;
    if (page != 1) {
      if (page > totalpage) {
        return;
      }
    }
    wx.request({
      url: app.myUlife.ulifeUrl + 'jfsc/getShangpinAll.html',
      data: {
        page: page,
        limit: limit
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        var sp = res.data.list;
        var totalpage = res.data.totalpage;
        var totalnum = res.data.totalnum;
        var jfsp = that.data.jfsp;
        for (var i = 0; i < sp.length; i++) {
          jfsp.push(sp[i]);
        }
        that.setData({
          jfsp: jfsp,
          totalpage: totalpage,
          totalnum: totalnum,
          'prompt.hidden': jfsp.length
        })
      }
    })
  },
  
  getMyJfyCh() {
    var usid = wx.getStorageSync('usid');
    var that = this;
    wx.request({
      url: app.myUlife.ulifeUrl + 'jfsc/getmyjfych.html',
      data: {
        usid: usid
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        var jfych = res.data;
        var kyjf=0;
        var alljf = 0;
        if (jfych.JFNUM){
          kyjf = jfych.JFNUM;
          alljf=jfych.JFNUM;
        }
        if (jfych.USEJF){
          kyjf = parseInt(kyjf) - parseInt(jfych.USEJF)
        }
        that.setData({
          jfych: jfych,
          kyjf:kyjf,
          alljf: alljf,
        })
      }
    })
  },



 




  //打开确认兑换框
  jfdhShow(e) {
    var currentStatu = e.currentTarget.dataset.statu; 
    this.util(currentStatu);
  },


  util: function (currentStatu) {
    // 用that取代this，防止不必要的情况发生
    var that = this;
    // 创建一个动画实例
    var animation = wx.createAnimation({
      // 动画持续时间
      duration:200,
      // 定义动画效果，当前是匀速
      timingFunction: 'linear',
      delay: 0 //0则不延迟  
    })
    // 将该变量赋值给当前动画
    that.animation = animation
    // 先在y轴偏移，然后用step()完成一个动画
    animation.opacity(0).translateY(200).step()
    // 用setData改变当前动画
    that.setData({
      // 通过export()方法导出数据
      animationData: animation.export(),
    })

    // 设置setTimeout来改变y轴偏移量，实现有感觉的滑动
    setTimeout(function () {
      animation.opacity(1).translateY(0).step()
      that.setData({
        animationData: animation.export()
      })

      //关闭  
      if (currentStatu == "close") {
        that.setData({
          showModalStatus: false
        });
      }
    }, 200)

    // 显示  
    if (currentStatu == "open") {
      that.setData({
        showModalStatus: true
      });
    }

  },



  openjfdh(e) {
    var index = e.currentTarget.dataset.index; 
    var jfsp=this.data.jfsp;
    var sp = jfsp[index];
    var kc = parseInt(sp.ALLNUM) - parseInt(sp.DHJL);
    if (kc<=0){
      wx.showModal({
        title: '友情提示',
        content: '对不起，该商品没有库存了!',
        showCancel: !1,
      })
      return;
    }
    this.setData({
      sp: sp,
      usejf: sp.NEEDJF,
      dhsl:1,
    })
    this.util("open");
  },

  adddhsl(){
    var dhsl = this.data.dhsl;
    var sp = this.data.sp;
    var sysl = sp.ALLNUM - sp.YDH;
    if (parseInt(dhsl) == parseInt(sysl)){
      return;
    }else{
      var needdhsl = parseInt(dhsl) + 1;
      var needjf = sp.NEEDJF;
      var usejf = parseInt(needjf) * parseInt(needdhsl);
      this.setData({
        dhsl: needdhsl,
        usejf: usejf
      })
    }
  },

  subdhsl() {
    var dhsl = this.data.dhsl;
    if (parseInt(dhsl) == 1) {
      return;
    } else {
      var sp = this.data.sp;
      var needdhsl = parseInt(dhsl) - 1;
      var needjf = sp.NEEDJF;
      var usejf = parseInt(needjf) * parseInt(needdhsl);
      this.setData({
        dhsl: needdhsl,
        usejf: usejf
      })
    }
  },

  addjfdhjl(e) {
    var that=this;
    var sp=this.data.sp;
    var usid = wx.getStorageSync('usid');
    var sname = wx.getStorageSync('name');
    var nj = wx.getStorageSync('nj');
    var bj = wx.getStorageSync('bj');
    var spid = sp.SPID;
    var usejf = this.data.usejf;
    var sflq = "0";
    var dhsl = this.data.dhsl;
    var myjf = this.data.kyjf;

    if (parseInt(usejf) > parseInt(myjf)){
      wx.showModal({
        title: '友情提示',
        content: '对不起，您的积分不够!',
        showCancel: !1,
      })
      return;
    }
    wx.showLoading({
      title: '保存中',
    })

    wx.request({
      url: app.myUlife.ulifeUrl + 'jfsc/addjfdhjl.html',
      data: {
        usid: usid,
        sname: sname,
        nj: nj,
        bj: bj,
        spid: spid,
        usejf: usejf,
        sflq: sflq,
        dhsl: dhsl
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.result) {
          that.util("close");
          that.tsopen("open");

          //查询可用积分与称号
          that.getMyJfyCh();
          //查询积分商城商品
          that.getShangpinAll();
          that.setData({
            page: 1,
            limit: 20,
            totalpage: 0,
            totalnum: 0,
            jfsp: [],
          })
        } else {
          wx.showModal({
            title: '失败',
            content: "数据保存失败！",
            showCancel: !1,
          });
        }
      }
    })

  
  },


  tishiShow(e) {
    var currentStatu = e.currentTarget.dataset.statu;
    this.tsopen(currentStatu);
  },

  tsopen: function (currentStatu) {
    /* 动画部分 */
    // 第1步：创建动画实例   
    var animation = wx.createAnimation({
      duration: 200, //动画时长  
      timingFunction: "linear", //线性  
      delay: 0 //0则不延迟  
    });

    // 第2步：这个动画实例赋给当前的动画实例  
    this.animation = animation;

    // 第3步：执行第一组动画  
    animation.opacity(0).rotateX(-100).step();

    // 第4步：导出动画对象赋给数据对象储存  
    this.setData({
      animationData: animation.export()
    })

    // 第5步：设置定时器到指定时候后，执行第二组动画  
    setTimeout(function () {
      // 执行第二组动画  
      animation.opacity(1).rotateX(0).step();
      // 给数据对象储存的第一组动画，更替为执行完第二组动画的动画对象  
      this.setData({
        animationData: animation
      })
      //关闭  
      if (currentStatu == "close") {
        this.setData({
          showTSModalStatus: false
        });
      }
    }.bind(this), 200)
    // 显示  
    if (currentStatu == "open") {
      this.setData({
        showTSModalStatus: true
      });
    }
  },



  
  zsShow(e) {
    var currentStatu = e.currentTarget.dataset.statu;
    this.zsopen(currentStatu);

    //获取当前时间
    // 调用函数时，传入new Date()参数，返回值是日期和时间
    var formatDate = util.formatDate(new Date());
    // 再通过setData更改Page()里面的data，动态更新页面的数据
    this.setData({
      formatDate: formatDate
    });
  },


  zsopen: function (currentStatu) {
    /* 动画部分 */
    // 第1步：创建动画实例   
    var animation = wx.createAnimation({
      duration: 200, //动画时长  
      timingFunction: "linear", //线性  
      delay: 0 //0则不延迟  
    });

    // 第2步：这个动画实例赋给当前的动画实例  
    this.animation = animation;

    // 第3步：执行第一组动画  
    animation.opacity(0).rotateX(-100).step();

    // 第4步：导出动画对象赋给数据对象储存  
    this.setData({
      animationData: animation.export()
    })

    // 第5步：设置定时器到指定时候后，执行第二组动画  
    setTimeout(function () {
      // 执行第二组动画  
      animation.opacity(1).rotateX(0).step();
      // 给数据对象储存的第一组动画，更替为执行完第二组动画的动画对象  
      this.setData({
        animationData: animation
      })
      //关闭  
      if (currentStatu == "close") {
        this.setData({
          showZsModalStatus: false
        });
      }
    }.bind(this), 200)
    // 显示  
    if (currentStatu == "open") {
      this.setData({
        showZsModalStatus: true
      });
    }
  },


  /**
     * 生命周期函数--监听页面初次渲染完成
     */
  onShow: function () {
    var that = this;
    var context = wx.createCanvasContext('share')
    context.setStrokeStyle("#00ff00")
    context.setLineWidth(1)
    context.stroke()
    context.draw(false, this.getTempFilePath);

  },

  //获取临时路径
  getTempFilePath: function () {
    wx.canvasToTempFilePath({
      canvasId: 'share',
      success: (res) => {
        this.setData({
          shareTempFilePath: res.tempFilePath
        })
      }
    })
  },

  //下载图片
  downlaodimageurl() {
    var that = this;
    wx.downloadFile({
      url: that.data.certifaceurl,
      success: function (res) {
        that.setData({
          tempFilePath: res.tempFilePath
        })
      },
      fail: function (res) {
      }
    });
  },


  //保存至相册
  saveImageToPhotosAlbum: function () {
    var that = this;
    that.setData({
      canvasHidden: false
    })
    //1. canvas绘制文字和图片
    const ctx = wx.createCanvasContext('share');

    //这里很重要，主要就是布局
    ctx.fillStyle = "#FFFFFF";
    ctx.fillRect(0, 0, 172, 252);
    ctx.drawImage(that.data.tempFilePath, 0, 0, 172, 252);
    
    ctx.font = "10px PingFangSC-Semibold,PingFangSC";
    ctx.fillStyle = "#646E97";


    ctx.textAlign = "center";
    ctx.fillText(that.data.username, 84, 112)

    ctx.font = "18px FZZYJW--GB1-0,FZZYJW--GB1";
    ctx.fillStyle = "#BF9156";

    ctx.fillText(that.data.jfych.CH, 84, 150);

    ctx.font = "9px DIN";
    ctx.fillStyle = "#BF9156";
    ctx.fillText(that.data.formatDate, 84, 225);

    ctx.stroke();
    ctx.draw(false, () => {
      // 3. canvas画布转成图片
      wx.canvasToTempFilePath({
        x: 0,
        y: 0,
        width: 375,
        height: 580,
        destWidth: 375,
        destHeight: 580,
        canvasId: 'share',
        success: function (res) {
          that.setData({
            shareImgSrc: res.tempFilePath
          })
          if (!res.tempFilePath) {
            wx.showModal({
              title: '提示',
              content: '图片绘制中，请稍后重试',
              showCancel: false
            })
          }
          //4. 当用户点击分享到朋友圈时，将图片保存到相册
          wx.saveImageToPhotosAlbum({
            filePath: that.data.shareImgSrc,
            success(res) {
              wx.showModal({
                title: '成功',
                content: '图片成功保存到相册了',
                showCancel: false,
              })
            },
            complete(){
              that.setData({
                canvasHidden: true
              })
            },
          })
        },
        fail: function (res) {
          if (res.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
            wx.openSetting({
              success(settingdata) {
       
                if (settingdata.authSetting['scope.writePhotosAlbum']) {
                  wx.showModal({
                    title: '成功',
                    content: '获取权限成功,请重新点击下载图片',
                    showCancel: false,
                  })
                } else {
                  wx.showModal({
                    title: '失败',
                    content: '获取权限失败',
                    showCancel: false,
                  })
                }
              }
            })
          }
          that.setData({
            canvasHidden: true
          }) 
        }
      })
    })
  },



  //切换
  onTapTag(e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    if (index == 1) {
      wx.navigateTo({
        url: '../czjl/home/home'
      })
    }else{
      that.setData({
        activeIndex: index,
      })
    }
  },

  //切换登录
  qiehuandl(e) {
    wx.removeStorageSync('dlzh');
    wx.removeStorageSync('name');
    wx.removeStorageSync('sex');
    wx.removeStorageSync('identity');
    wx.removeStorageSync('nj');
    wx.removeStorageSync('bj');
    wx.removeStorageSync('usid');
    wx.removeStorageSync('user_type');
    wx.reLaunch({
      url: '../../pages/login/login'
    })
  },


  errorFunction: function (e) {
    if (e.type == "error") {
      this.setData({
        topimage: this.data.imgdefalut
      })
    }
  },


//...................授权获取用户基本信息......................

  opensqdl(){
    var gender = this.data.gender;
    if (gender == '未授权登录') {
      this.qrsqopen("open");
    }
  },
  qrsqShow(e) {
    var currentStatu = e.currentTarget.dataset.statu;
    this.qrsqopen(currentStatu);
  },
  cancelopen(){
    this.qrsqopen("close");
  },
  qrsqopen: function (currentStatu) {
    /* 动画部分 */
    // 第1步：创建动画实例   
    var animation = wx.createAnimation({
      duration: 200, //动画时长  
      timingFunction: "linear", //线性  
      delay: 0 //0则不延迟  
    });

    // 第2步：这个动画实例赋给当前的动画实例  
    this.animation = animation;

    // 第3步：执行第一组动画  
    animation.opacity(0).rotateX(-100).step();

    // 第4步：导出动画对象赋给数据对象储存  
    this.setData({
      animationData: animation.export()
    })

    // 第5步：设置定时器到指定时候后，执行第二组动画  
    setTimeout(function () {
      // 执行第二组动画  
      animation.opacity(1).rotateX(0).step();
      // 给数据对象储存的第一组动画，更替为执行完第二组动画的动画对象  
      this.setData({
        animationData: animation
      })
      //关闭  
      if (currentStatu == "close") {
        this.setData({
          showsqModalStatus: false
        });
      }
    }.bind(this), 200)
    // 显示  
    if (currentStatu == "open") {
      this.setData({
        showsqModalStatus: true
      });
    }
  },


  onGotUserInfo(e) {
    wx.removeStorageSync('city');
    wx.removeStorageSync('province');
    wx.removeStorageSync('gender');
    wx.removeStorageSync('nickName');
    wx.removeStorageSync('avatarUrl');

    //加入缓存
    var userInfo = e.detail.userInfo;
    wx.setStorageSync('city', userInfo.city);
    wx.setStorageSync('province', userInfo.province);
    wx.setStorageSync('gender', userInfo.gender);
    wx.setStorageSync('nickName', userInfo.nickName);
    wx.setStorageSync('avatarUrl', userInfo.avatarUrl);

    this.setData({
      gender: userInfo.gender,
      avatarUrl: userInfo.avatarUrl,
    });
    this.qrsqopen("close");
  },


//...................授权获取用户基本信息end......................

  //帮助文档
  helpdoc(){
    wx.navigateTo({
      url: '../operation/index'
    })
  },
  
})